package util;


import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Id工具类
 * 
 * @author super_dev_001<br />
 *
 * @since  software platform v1.0.0
 * @version 1.0.0 <br />
 *          <table border="1" cellpadding="3" cellspacing="0">
 *          <tr>
 *          <th align="left" colspan="3"><b>修改历史</b></th>
 *          </tr>
 *          <tr>
 *          <td>修改日期</td>
 *          <td>修改人</td>
 *          <td>修改描述</td>
 *          </tr>
 *          <tr>
 *          <td>2018-6-20</td>
 *          <td>super_dev_001</td>
 *          <td>新建</td>
 *          </tr>
 *          </table>
 */
public class IdUtils {

	private AtomicInteger sequence = new AtomicInteger();
	private long prefix;
	private volatile long timestamp;
	private volatile int increment;

	private static IdUtils instance = new IdUtils();

	private IdUtils() {
		prefix = ((prefix & 0x0FFF) << 52) & 0xFFF0000000000000L;
	}

	public static long id() {
		long timestamp = (((System.currentTimeMillis() / 1000) & 0xFFFFFFFFL) << 20) & 0x0FFFFFFFF00000L;
		int increment = instance.sequence.getAndIncrement() & 0x0FFFFF;

		if (timestamp <= instance.timestamp) {
			while (timestamp < instance.timestamp) {
				timestamp += 0x100000L;
			}
			if (increment == instance.increment) {
				timestamp += 0x100000L;
			}
		} else {
			instance.increment = increment;
		}
		instance.timestamp = timestamp;

		return instance.prefix + timestamp + increment + 8;
	}

	public static String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public static void main(String[] args) {
		System.out.println(IdUtils.id());
	}

}
